<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-5-11
 * Time: 9:11
 */

namespace app\web\controller;

use app\common\model\Minus as MinusModel;
use app\common\service\MinusService;
use app\web\validate\MinusValidate;
use think\Db;

class Minus extends Auth
{

    /**
     * 项目减免列表
     * @return mixed
     * @throws \think\Exception
     */
    public function index()
    {
        if ($this->request->isPost()) {

            $limit = $this->request->post('limit') ?? 10;
            // 数据列表
            $data_list = MinusModel::order('sort asc,id desc')->paginate($limit);
            foreach ($data_list as $k => $v) {
                $names = MinusModel::alias('m')
                    ->leftJoin('dp_qt_data_minus_item i', 'i.minus_id=m.id')
                    ->leftJoin('dp_qt_project p', 'p.id=i.item_id')
                    ->where(['i.minus_id' => $v['id'], 'i.source' => 1])
                    ->column('i.name');

                $nameds = MinusModel::alias('m')
                    ->leftJoin('dp_qt_data_minus_item i', 'i.minus_id=m.id')
                    ->leftJoin('dp_qt_project p', 'p.id=i.item_id')
                    ->where(['i.minus_id' => $v['id'], 'i.source' => 2])
                    ->column('i.name');

                //减免规则
                $data_list[$k]['rule'] = $v['type_ed'] == 1 ? '按照项目' : "按照金额" ;
                $data_list[$k]['type'] = $v['type'] == 1 ? '按项目' : '按金额';
                $hand_card_type_config = [1=>'消费手牌',2=> '男宾手牌',3=> '女宾手牌',4=> '儿童手牌',5=> '其他手牌',6=> 'viper手牌'];
                $hand_card_type_name = '';

                if (!empty($v['hand_card_type'])) {
                    foreach (explode(',',$v['hand_card_type']) as $key => $val) {
                        $hand_card_type_name .= $hand_card_type_config[$val].',';
                    }
                }
                $data_list[$k]['hand_card_type'] = !empty($hand_card_type_name) ? rtrim($hand_card_type_name,',') : '';
                $data_list[$k]['range'] = $v['range_start'] && $v['range_end'] ? intval($v['range_start']) . '-' . intval($v['range_end']) : '-';
                $data_list[$k]['project_name'] = implode(',', $names);
                $data_list[$k]['projected_name'] = implode(',', $nameds);
                $real_name = Db::name('qt_users')->field('real_name')->where('id',$v['updater'])->value('real_name');
                $data_list[$k]['updater'] = $real_name ?? '';

            }
            $this->result('查询成功', $data_list, 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 添加减免
     * @return mixed
     * @throws \think\Exception
     */
    public function add()
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $post = $this->request->post();

            $validate = new MinusValidate();
            if (!$validate->scene('add')->check($post)) {
                $this->result($validate->getError(), '', 204);
            }

            //验证字段
            $info = MinusModel::get(['name' => $post['name']]);
            if ($info) $this->result('减免项目名称已经存在', '', 204);

            Db::startTrans();

            try{

                $userInfo = $this->userInfo;
                $post['creater'] = $post['updater'] = $userInfo['id'];
                $minus_model = MinusModel::create($post);

                //写减免的项目商品
                if (!empty($post['reduction'])) {
                    $reduction = json_decode($post['reduction'], true);
                    $status = MinusService::saveMinusItem($minus_model['id'], $reduction, 1);
                    if($status['status'] == false){
                        $this->result($status['msg'], '', 204);
                    }
                }
                //写被减免的项目商品
                if (!empty($post['be_reduced'])) {
                    $be_reduced = json_decode($post['be_reduced'], true);
                    $status =  MinusService::saveMinusItem($minus_model['id'], $be_reduced, 2);
                    if($status['status'] == false){
                        $this->result($status['msg'], '', 204);
                    }
                }
                // 提交事务
                Db::commit();
            }catch (\Exception $exception){

                // 回滚事务
                Db::rollback();
                $this->result('新增失败'.$exception->getMessage(), '', 204);
            }

            return $this->result('新增成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 编辑套餐
     * @param null $id
     * @return mixed
     * @throws \think\Exception
     */
    public function edit()
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $post = $this->request->post();

            $validate = new MinusValidate();
            if (!$validate->scene('edit')->check($post)) {
                $this->result($validate->getError(), '', 204);
            }

            $minus_id = $post['id'];

            //验证字段
            $is_exits = Db::name('qt_data_minus')->field('id')
                ->where(['name'=>$post['name']])
                ->where('id','<>',$minus_id)
                ->find();
            if ($is_exits) $this->result('减免项目名称已经存在', '', 204);

            Db::startTrans();
            try {
                $userInfo = $this->userInfo;
                $post['updater'] = $userInfo['id'];
                $minus_model = MinusModel::update($post);

                //先删除
                Db::name("qt_data_minus_item")->where(['minus_id'=>$minus_id])->delete();
                //写减免的项目
                if (!empty($post['reduction'])) {
                    $reduction = json_decode($post['reduction'], true);
                    MinusService::saveMinusItem($minus_model['id'], $reduction, 1);
                }

                //写被减免的项目
                if (!empty($post['be_reduced'])) {
                    $be_reduced = json_decode($post['be_reduced'], true);

                    MinusService::saveMinusItem($minus_model['id'], $be_reduced, 2);
                }

                // 提交事务
                Db::commit();
            }catch (\Exception $exception){

                Db::rollback();
                $this->result('编辑失败'.$exception->getMessage(), '', 204);
            }

            $this->result('编辑成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 获取减免信息详情
     */
    public function getMinusInfo(){

        if ($this->request->isPost()) {
            // 表单数据
            $post = $this->request->post();
            if (empty($post['id'])) {
                $this->result('ID字段必填', '', 204);
            }
            $minus_id = $post['id'];

            $minus_data = MinusModel::where(['id'=>$minus_id])->find();

            $reduction = Db::name('qt_data_minus_item')
                ->where('minus_id', $minus_id)->where(['source'=>1])->column("CONCAT_WS('-',item_type,item_id)");

            $be_reduced = Db::name('qt_data_minus_item')
                ->where('minus_id', $minus_id)->where(['source'=>2])->column("CONCAT_WS('-',item_type,item_id)");

            //减免规则
            $minus_data['range'] = $minus_data['range_start'] && $minus_data['range_end'] ? intval($minus_data['range_start']) . '-' . intval($minus_data['range_end']) : '-';
            $minus_data['reduction'] = $reduction;
            $minus_data['be_reduced'] = $be_reduced;

            $this->result('查询成功', $minus_data, 200);

        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 获取下拉选项
     */
    public function getMinusConfig () {

        $list['minus_type'] = [['id'=>1, 'name'=> '按照项目'],['id'=>2,'name'=> '按照金额']];
        $list['hand_card_type'] = [['id'=>1, 'name'=> '消费手牌'],['id'=>2,'name'=> '男宾手牌'],['id'=>3,'name'=> '女宾手牌'],['id'=>4,'name'=> '儿童手牌'],['id'=>5,'name'=> '其他手牌'],['id'=>6,'name'=> 'viper手牌']];
        $list['computer_type'] = [['id'=>1, 'name'=> '按手牌计算单独计算'],['id'=>1, 'name'=> '整单一起计算']];

        $this->result('查询成功', $list, 200);
    }


    /**
     * 删除减免信息
     */
    public function remove () {

        if ($this->request->isPost()) {
            // 表单数据
            $post = $this->request->post();
            if (empty($post['id'])) {
                $this->result('ID字段必填', '', 204);
            }
            $minus_id = $post['id'];

            $minus_data = MinusModel::where(['id'=>$minus_id])->find();
            if (!$minus_data){
                $this->result('减免项目不存在存在', '', 204);
            }

            Db::name("qt_data_minus")->where(['id'=>$minus_id])->delete();
            Db::name("qt_data_minus_item")->where(['minus_id'=>$minus_id])->delete();

            $this->result('删除成功', '', 200);

        }
        $this->result('无效的请求', '', 204);
    }

}